package com.story.modular.app.controller.radio;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.story.common.annotion.BussinessLog;
import com.story.common.constant.Dict;
import com.story.common.constant.factory.PageFactory;
import com.story.common.exception.BizExceptionEnum;
import com.story.common.exception.BussinessException;
import com.story.common.persistence.dao.*;
import com.story.common.persistence.model.*;
import com.story.config.properties.ChildProperties;
import com.story.config.properties.UpyunProperties;
import com.story.core.base.controller.BaseController;
import com.story.core.shiro.ShiroKit;
import com.story.core.support.BeanKit;
import com.story.core.util.RegExpValidatorUtil;
import com.story.core.util.ToolUtil;
import com.story.core.util.UriUtil;
import com.story.modular.app.dao.*;
import com.story.modular.app.service.UpyunService;
import com.story.modular.app.service.VedioService;
import com.story.modular.app.transfer.UpdateVedioDto;
import com.story.modular.app.transfer.AudioAddDto;
import com.story.modular.app.warpper.ResultVo;
import com.story.modular.app.warpper.VedioDto;
import com.story.modular.app.warpper.VedioWarpper;
import io.swagger.annotations.Api;
import main.java.com.UpYun;
import main.java.com.upyun.UpException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author Administrator
 * @decription 音频管理
 * @Date 2017-12-22 11:17
 */
@Controller
@RequestMapping(value = "/vedio/radio")
public class RadioVedioController extends BaseController{

    private static final String PREFIX = "/app/vedio/radio/";

    private static final Long EXPIRE_TIME = 3600L;

    @Autowired
    private AudioDetailDao audioDetailDao;

    @Autowired
    private ChildProperties childProperties;

    @Autowired
    private VedioService vedioService;

    @Autowired
    private VedioCategoryDao vedioCategoryDao;

    @Autowired
    private AudioDetailMapper audioDetailMapper;

    @Autowired
    private VedioCategoryMapper vedioCategoryMapper;

    @Autowired
    private SongListDetailDao songListDetailDao;

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UpYun upyun;

    @Autowired
    private CateVedioDao cateVedioDao;

    @Autowired
    private VedioAgeDao vedioAgeDao;

    @Autowired
    private BannerMapper bannerMapper;



    /**
     * 进入首页
     * @return
     */
    @RequestMapping(value = "")
    public String index() {
        return PREFIX + "radio.html";
    }
    @RequestMapping(value = "/batch")
    public String batch_upload(Model model){
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //查询所有专辑
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
        if(categoryList.isEmpty()) {
            throw new BussinessException(BizExceptionEnum.CATES_NULL);
        }
        model.addAttribute("bannerList",bannerMapList);
        model.addAttribute("cateList",categoryList);
        return PREFIX+"radio_batch_upload.html";
    }
    /**
     * 进入excel批量添加页面
     * @return
     */
    @RequestMapping(value = "/toExcelAdd")
    public String excelAdd() {
        return PREFIX + "radio_excel_upload.html";
    }

    /**
     * 进入新新增页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/vedioAdd")
    public String toAdd(Model model) {
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //查询所有专辑
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
        if(categoryList.isEmpty()) {
            throw new BussinessException(BizExceptionEnum.CATES_NULL);
        }
        model.addAttribute("bannerList",bannerMapList);
        model.addAttribute("cateList",categoryList);
        return PREFIX + "radio_add.html";
    }

    /**
     * 进入修改页面
     * @param vedioId
     * @param model
     * @return
     */
    @RequestMapping(value = "vedioUpdate/{vedioId}")
    public String toUpdate(@PathVariable(value = "vedioId") Integer vedioId, Model model) {
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>();
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //查询该音频的信息
        Map<String,Object> vedioDetailMap = audioDetailDao.getVedioDetailById(vedioId);
        //查询所有专辑和对应年龄段,处理是否选中
         List<VedioCategory> categoryList = vedioCategoryMapper.selectList(new EntityWrapper<VedioCategory>().eq("resType",0));
         List<Map<String,Object>> cateList = new ArrayList<Map<String,Object>>();
        for (VedioCategory vedioCategory : categoryList) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("name",vedioCategory.getName());
            map.put("id",vedioCategory.getId());
            boolean flag = false;
            if(StringUtils.isNotBlank((String)vedioDetailMap.get("cateId"))) {
                String[] cateIds = ((String)vedioDetailMap.get("cateId")).split(",");
                for (int i = 0; i < cateIds.length; i++) {
                    if(vedioCategory.getId() == Integer.parseInt(cateIds[i])) {
                        flag = true;
                        map.put("checked","true");
                    } else {
                        continue;
                    }
                }
            }
            if(!flag) {
                map.put("checked","false");
            }
            cateList.add(map);
        }
        vedioDetailMap.put("cateList",cateList);
        //加入cateNames字段
        if(StringUtils.isNotBlank((String)vedioDetailMap.get("cateId"))) {
            String[] cateIds = ((String)vedioDetailMap.get("cateId")).split(",");
            List<Integer> cateIdList = new ArrayList<>(cateIds.length);
            for (int i = 0; i < cateIds.length; i++) {
                cateIdList.add(Integer.parseInt(cateIds[i]));
            }
            vedioDetailMap.put("cateNames",vedioCategoryDao.getCateNameById(cateIdList));
        }
        //加入ageTypeNames字段返回
        List<Integer> ageTypeIdList = new ArrayList<>();
        if(StringUtils.isNotBlank((String)vedioDetailMap.get("ageType"))) {
            String[] ageTypeIds = ((String)vedioDetailMap.get("ageType")).split(",");
            String ageTypeNames = this.getAgeTypeNames(ageTypeIds);
            vedioDetailMap.put("ageTypeNames",ageTypeNames);
            //将ageTypeId转为List集合
            for (int i = 0; i < ageTypeIds.length; i++) {
                ageTypeIdList.add(Integer.parseInt(ageTypeIds[i]));
            }
            vedioDetailMap.put("ageTypeIdList",ageTypeIdList);
        }
        //移除原来的cateId
        vedioDetailMap.remove("cateId");

        vedioDetailMap.remove("ageType");

        vedioDetailMap.put("logoPath",upyunProperties.getDomain() + vedioDetailMap.get("logoPath"));
        vedioDetailMap.put("filePath",upyunProperties.getDomain() + vedioDetailMap.get("filePath"));

        model.addAttribute("bannerList",bannerList);
        model.addAttribute("vedioDetail",vedioDetailMap);
        return PREFIX + "vedio_update.html";
    }

    @BussinessLog(value = "修改音频", key = "id", dict = Dict.VedioDict)
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object updateVedio(AudioAddDto vedioDto) throws IOException, UpException {
        if(ToolUtil.isOneEmpty(vedioDto,vedioDto.getVedioName(),vedioDto.getLogoPath(),vedioDto.getFilePath(),vedioDto.getCateList(),vedioDto.getAgeType())) {
            throw new BussinessException( BizExceptionEnum.REQUEST_NULL);
        }
        AudioDetail vedioDetail = new AudioDetail();
        BeanKit.copyProperties(vedioDto,vedioDetail);
        vedioDetail.setName(vedioDto.getVedioName());
        if(vedioDetail.getRating() > 5 || vedioDetail.getRating() < 1) {
            vedioDetail.setRating(5);
        }
        //处理logo地址
        vedioDetail.setLogoPath(getUrl(vedioDetail.getLogoPath(),"logo"));
        //处理音频地址
        vedioDetail.setFilePath(getUrl(vedioDetail.getFilePath(),"play"));
        checkCount(vedioDetail.getPlayCount(),"play");
        checkCount(vedioDetail.getShareCount(),"share");
        checkCount(vedioDetail.getDownloadCount(),"download");
        audioDetailMapper.updateById(vedioDetail);
        //处理音频与年龄段，音频与专辑的关系
        List<String> ageTypeIds = Arrays.asList(vedioDto.getAgeType().split(","));
        List<String> cateVedioIds = Arrays.asList(vedioDto.getCateList().split(","));
        List<Integer> oldAgeTypsId = vedioAgeDao.getAgeTypeByVedioId(vedioDto.getId());
        List<Integer> oldCateIds = cateVedioDao.getCateIdsByVedioId(vedioDto.getId());
        for (Integer oldAgeTypeId : oldAgeTypsId) {
            if(!ageTypeIds.contains(String.valueOf(oldAgeTypeId))) {
                vedioAgeDao.deleteByIds(vedioDto.getId(),oldAgeTypeId);
            }
        }
        List<Integer> insertAgeId = new ArrayList<>();
        for (String ageTypeId : ageTypeIds) {
            Integer ageTypeIntId = Integer.parseInt(ageTypeId);
            if(!oldAgeTypsId.contains(ageTypeIntId)) {
                insertAgeId.add(ageTypeIntId);
            }
        }
        if(!insertAgeId.isEmpty()) {
            vedioAgeDao.batchInsertAgeType(insertAgeId,vedioDto.getId());
        }
        for (Integer oldCateId : oldCateIds) {
            if(!cateVedioIds.contains(String.valueOf(oldCateId))) {
                cateVedioDao.deleteByIds(vedioDto.getId(),oldCateId);
            }
        }
        List<Integer> insertCateId = new ArrayList<>();
        for (String cateVedioId : cateVedioIds) {
            Integer cateVedioIntId = Integer.parseInt(cateVedioId);
            if(!oldCateIds.contains(cateVedioIntId)) {
                insertCateId.add(cateVedioIntId);
            }
        }
        if(!insertCateId.isEmpty()) {
            cateVedioDao.batchInsertCateVedioId(insertCateId,vedioDto.getId());
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 进入批量修改页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/batchUpPage")
    public String batchUpdatePage(Model model) {
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<String,Object>(4);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        //查询所有专辑和对应年龄段
        List<VedioCategory> categoryList = vedioCategoryMapper.selectList(new EntityWrapper<VedioCategory>().eq("resType",0));
        List<Map<String,Object>> cateList = new ArrayList<Map<String,Object>>();
        for (VedioCategory vedioCategory : categoryList) {
            Map<String,Object> map = new HashMap<String,Object>(4);
            map.put("id",vedioCategory.getId());
            map.put("name",vedioCategory.getName());
            cateList.add(map);
        }
        model.addAttribute("bannerList",bannerMapList);
        model.addAttribute("categoryList",cateList);
        return PREFIX + "radio_batch_update.html";
    }

    /**
     * 批量修改音频所属
     * @param updateVedioDto
     * @return
     */
    @BussinessLog(value = "批量修改", key = "id", dict = Dict.VedioDict)
    @RequestMapping(value = "/batchUpCate")
    @ResponseBody
    public Object batchUpCateId(UpdateVedioDto updateVedioDto) {
        if(ToolUtil.isOneEmpty(updateVedioDto,updateVedioDto.getCateId(),updateVedioDto.getIds())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        List<Integer> idList = new ArrayList<Integer>();
        String[] idArray = updateVedioDto.getIds().split(",");
        for (String id : idArray) {
            idList.add(Integer.valueOf(id));
        }
        List<Integer> cateIdList = new ArrayList<>();
        String[] cateArray = updateVedioDto.getCateId().split(",");
        for (String cateIdStr : cateArray) {
            cateIdList.add(Integer.parseInt(cateIdStr));
        }
        cateVedioDao.deleteRelationByVedioId(idList);
        for (Integer cateId : cateIdList) {
            cateVedioDao.batchBindCateId(idList,cateId);
        }
        return super.SUCCESS_TIP;
    }

    @BussinessLog(value = "删除音频", key = "id", dict = Dict.DeleteDict)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object deleteVedio(@RequestParam(value = "vedioIds") String vedioIds) {
        String[] vedioIdSArr = vedioIds.split(",");
        List<Integer> vedioIdList = new ArrayList<Integer>(vedioIdSArr.length);
        for (String vedioId : vedioIdSArr) {
            vedioIdList.add(Integer.valueOf(vedioId));
        }
        //解除用户收藏单与音频的关联关系
        songListDetailDao.deleteSongListDetailByVedioId(vedioIdList);
        //解绑与年龄段的关联
        vedioAgeDao.deleteRelationByVedioId(vedioIdList);
        //解绑与所属转接的关联
        cateVedioDao.deleteRelationByVedioId(vedioIdList);
        //删除该音频
        audioDetailDao.batchDeleteVedio(vedioIdList);
        return super.SUCCESS_TIP;
    }

    @BussinessLog(value = "批量新增音频", key = "name", dict = Dict.VedioDict)
    @RequestMapping("/addBatchRadio")
    @ResponseBody
    public Object addBatch(){
        return null;
    }
    @BussinessLog(value = "批量新增音频", key = "name", dict = Dict.VedioDict)
    @RequestMapping("/addBatchVideo")
    @ResponseBody
    public Object addBatch(@RequestParam String data) throws IOException, UpException {
        //JSONObject jsonObject = JSONObject.parseObject(data);
        //CommonUtil.unicodeToUtf8(data);
        JSONArray arrayList= JSONArray.parseArray(data);
        List<AudioAddDto> vList = JSONObject.parseArray(arrayList.toJSONString(), AudioAddDto.class);
        for(int j=0;j<vList.size();j++){
            AudioAddDto vedioDto=new AudioAddDto();
            vedioDto=vList.get(j);
            AudioDetail vedioDetail = new AudioDetail();
            BeanKit.copyProperties(vedioDto,vedioDetail);
            if(vedioDetail.getRating() > 5 || vedioDetail.getRating() < 1) {
                vedioDetail.setRating(5);
            }
            //音频图片处理
            vedioDetail.setLogoPath(getUrl(vedioDetail.getLogoPath(),"logo"));
            //音频播放地址处理
            vedioDetail.setFilePath(getUrl(vedioDetail.getFilePath(),"play"));

            checkCount(vedioDetail.getPlayCount(),"play");
            checkCount(vedioDetail.getShareCount(),"share");
            checkCount(vedioDetail.getDownloadCount(),"download");
            vedioDetail.setCreateTime(new Date());
            vedioDetail.setName(vedioDto.getVedioName());
            vedioDetail.setResType(0);
            //如果前台上传者为空，则使用当前用户名作为上传者
            if(StringUtils.isBlank(vedioDetail.getUploader())) {
                Integer id = ShiroKit.getUser().getId();
                User user = userMapper.selectById(id);
                vedioDetail.setUploader(user.getName());
            }
            //保存音频基础信息
            audioDetailMapper.insert(vedioDetail);
            //保存音频与年龄段的关系信息
            String[] ageTypesIds = vedioDto.getAgeType().split(",");
            for (int i = 0; i < ageTypesIds.length; i++) {
                VedioAge vedioAge = new VedioAge();
                vedioAge.setVedioId(vedioDetail.getId());
                vedioAge.setAgeType(Integer.parseInt(ageTypesIds[i]));
                vedioAgeDao.insert(vedioAge);
            }
            //保存音频与专辑的关系信息
            String[] cateVedioIds = vedioDto.getCateList().split(",");
            for (int i = 0; i < cateVedioIds.length; i++) {
                CateVedio cateVedio = new CateVedio();
                cateVedio.setVedioId(vedioDetail.getId());
                cateVedio.setCateId(Integer.parseInt(cateVedioIds[i]));
                cateVedioDao.insert(cateVedio);
            }
        }
        return super.SUCCESS_TIP;
    }
    /**
     * 新增音频
     * @param vedioDto
     * @return
     */
    @BussinessLog(value = "新增音频", key = "name", dict = Dict.VedioDict)
    @RequestMapping(value = "/add")
    @ResponseBody
    @Transactional(rollbackFor = RuntimeException.class)
    public Object add(AudioAddDto vedioDto) throws IOException, UpException {
        if(ToolUtil.isOneEmpty(vedioDto,vedioDto.getFilePath(),vedioDto.getVedioName(),vedioDto.getLogoPath(),vedioDto.getCateList(),vedioDto.getAgeType())) {
            throw new BussinessException( BizExceptionEnum.REQUEST_NULL);
        }
        AudioDetail vedioDetail = new AudioDetail();
        BeanKit.copyProperties(vedioDto,vedioDetail);
        if(vedioDetail.getRating() > 5 || vedioDetail.getRating() < 1) {
            vedioDetail.setRating(5);
        }
//        if(!RegExpValidatorUtil.isMintueAndSecond(vedioDetail.getDuration())) {
//            throw new BussinessException(BizExceptionEnum.DURATION_ERROR);
//        }
//        int maxOrderNum = vedioDetailDao.getMaxOrderNum(vedioDetail.getCateId());
//        if(vedioDetail.getOrderNum() <= maxOrderNum) {
//            vedioDetail.setOrderNum(maxOrderNum + 1);
//        }
        //音频图片处理
        vedioDetail.setLogoPath(getUrl(vedioDetail.getLogoPath(),"logo"));
        //音频播放地址处理
        vedioDetail.setFilePath(getUrl(vedioDetail.getFilePath(),"play"));

        checkCount(vedioDetail.getPlayCount(),"play");
        checkCount(vedioDetail.getShareCount(),"share");
        checkCount(vedioDetail.getDownloadCount(),"download");
        vedioDetail.setCreateTime(new Date());
        vedioDetail.setName(vedioDto.getVedioName());
        vedioDetail.setResType(0);
        //如果前台上传者为空，则使用当前用户名作为上传者
        if(StringUtils.isBlank(vedioDetail.getUploader())) {
            Integer id = ShiroKit.getUser().getId();
            User user = userMapper.selectById(id);
            vedioDetail.setUploader(user.getName());
        }
        //保存音频基础信息
        audioDetailMapper.insert(vedioDetail);
        //保存音频与年龄段的关系信息
        String[] ageTypesIds = vedioDto.getAgeType().split(",");
        for (int i = 0; i < ageTypesIds.length; i++) {
            VedioAge vedioAge = new VedioAge();
            vedioAge.setVedioId(vedioDetail.getId());
            vedioAge.setAgeType(Integer.parseInt(ageTypesIds[i]));
            vedioAgeDao.insert(vedioAge);
        }
        //保存音频与专辑的关系信息
        String[] cateVedioIds = vedioDto.getCateList().split(",");
        for (int i = 0; i < cateVedioIds.length; i++) {
            CateVedio cateVedio = new CateVedio();
            cateVedio.setVedioId(vedioDetail.getId());
            cateVedio.setCateId(Integer.parseInt(cateVedioIds[i]));
            cateVedioDao.insert(cateVedio);
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 得到音频列表
     * @param keyword
     * @param startTime
     * @param endTime
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(value = "keyword",required = false) String keyword,
                       @RequestParam(value = "beginTime",required = false) String startTime,
                       @RequestParam(value = "endTime",required = false) String endTime,
                       @RequestParam(value = "searchType",required = false) Integer searchType) {
        Page<AudioDetail> page = new PageFactory<AudioDetail>().defaultPage();
        if(searchType == 3) {
            if(keyword.contains("胎教")) {
                keyword = "0";
            }
            if(keyword.contains("0-1") || keyword.contains("0") || keyword.contains("0-") || keyword.contains("-1")) {
                keyword = "1";
            } else if(keyword.contains("1-3") ||keyword.contains("1") ||  keyword.contains("1-") || keyword.contains("-3")) {
                keyword = "2";
            } else if(keyword.contains("3-5") || keyword.contains("3") || keyword.contains("3-") || keyword.contains("-5") || keyword.contains("6")) {
                keyword = "3";
            } else if(keyword.contains("5-7") || keyword.contains("5") || keyword.contains("5-") || keyword.contains("-7") || keyword.contains("7")) {
                keyword = "4";
            } else if(keyword.contains("7") || keyword.contains("7-12") || keyword.contains("7-") || keyword.contains("-12") || keyword.contains("12")) {
                keyword = "5";
            } else {
                keyword = "all";
            }
        }
        List<Map<String,Object>> vedioDetailList = audioDetailDao.getVedioList(page, keyword.trim(),startTime,endTime,searchType,
                page.getOrderByField(), page.isAsc(),0);
        List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        for (Map map : vedioDetailList) {
            String cateNameStr = (String)map.get("cateName");
            if(StringUtils.isNotBlank(cateNameStr)) {
                String[] cateNames = cateNameStr.split(",");
                Integer[] cateNameInts = new Integer[cateNames.length];
                for (int i = 0; i < cateNames.length; i++) {
                    cateNameInts[i] = Integer.parseInt(cateNames[i]);
                }
                List<Integer> cateIds = Arrays.asList(cateNameInts);
                map.put("cateName",vedioCategoryDao.getCateNameById(cateIds));
            }
            map.put("filePath",upyunProperties.getDomain() + map.get("filePath"));
            map.put("logoPath",upyunProperties.getDomain() + map.get("logoPath"));
            if(StringUtils.isNotBlank((String) map.get("ageType"))) {
                String[] ageTypeStr = ((String) map.get("ageType")).split(",");
                String ageType = getAgeTypeNames(ageTypeStr);
                map.put("ageType",ageType);
            }
            result.add(map);
        }
        page.setRecords((List<AudioDetail>) new VedioWarpper(result).warp());
        return super.packForBT(page);
    }

    /**
     * excel模板下载
     * @throws Exception
     */
    @RequestMapping(value = "/excelDownload")
    public void excelDownload() throws Exception {
        HttpServletResponse response = super.getHttpServletResponse();
        HttpServletRequest request = super.getHttpServletRequest();
        response.setContentType("text/html;charset=UTF-8");
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        request.setCharacterEncoding("UTF-8");
        try {
            File f = new File(childProperties.getFileUploadPath() + File.separator + "template.xlsx");
            if(!f.exists()) {
                PrintWriter writer = response.getWriter();
                writer.print("<html>");
                writer.print("<script type=\"text/javascript\">");
                writer.print("window.top.close()");
                writer.print("</script>");
                writer.print("</html>");
                writer.flush();
                writer.close();
                return;
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-excel");
            response.setHeader("Content-Disposition", "attachment; filename=template.xlsx");
            response.setHeader("Content-Length",String.valueOf(f.length()));
            in = new BufferedInputStream(new FileInputStream(f));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] data = new byte[1024];
            int len = 0;
            while (-1 != (len=in.read(data, 0, data.length))) {
                out.write(data, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }

    }

    /**
     * excel批量新增
     * @param excelFile
     * @return
     */
    @RequestMapping(value = "/excelAdd")
    @ResponseBody
    public ResultVo excelBatchSave(@RequestPart("file") MultipartFile excelFile) {
        ImportParams params = new ImportParams();
        InputStream excelFileInputStream;
        try {
            excelFileInputStream = excelFile.getInputStream();
        } catch (IOException e) {
            return new ResultVo(500,"未能获取excel模板");
        }
        List<VedioDto> vedioDtoList;
        try {
            vedioDtoList = ExcelImportUtil.importExcel(excelFileInputStream, VedioDto.class, params);
        } catch (Exception e) {
            return new ResultVo(500,"excel解析有误，请检查");
        }

        return vedioService.excelBatchAdd(vedioDtoList);
    }

    /**
     * 一个栏目下的专辑
     * @param bannerId
     * @return
     */
    @RequestMapping(value = "/cateInBanner")
    @ResponseBody
    public List<Map<String,Object>> cateInBanner(@RequestParam(value = "bannerId") Integer bannerId) {
        bannerId = bannerId == 0 ? null : bannerId;
        List<Map<String,Object>> categoryList = vedioCategoryDao.getCateInBanner(bannerId,0);
        return categoryList;
    }

    /**
     * 一个栏目下的专辑
     * @param bannerIds
     * @return
     */
    @RequestMapping(value = "/cateInBanners")
    @ResponseBody
    public List<Map<String,Object>> cateInBanners(@RequestParam(value = "bannerIds") String bannerIds) {
        List<Map<String,Object>> categoryList = vedioCategoryDao.getAllCategory(0);
//        String[] bannerIds2=bannerIds.split(",");
//        Integer bannerId=0;
//        List<Map<String,Object>> categoryList=new ArrayList<>();
//        if (bannerIds2[0]!=""){
//            for (int i=0;i<bannerIds2.length;i++){
//                bannerId=Integer.parseInt(bannerIds2[i]);
//                bannerId = bannerId == 0 ? null : bannerId;
//                categoryList.addAll(vedioCategoryDao.getCateInBanner(bannerId,0));
//            }
//        }else {
//            bannerId = bannerId == 0 ? null : bannerId;
//            categoryList.addAll(vedioCategoryDao.getCateInBanner(bannerId,0));
//        }


        return categoryList;
    }

    @RequestMapping(value = "/cateInBanners2")
    @ResponseBody
    public List<Map<String,Object>> cateInBanners2(@RequestParam(value = "bannerIds") String bannerIds) {
        List<Banner> bannerList = bannerMapper.selectList(new EntityWrapper<Banner>().eq("type",0));
        List<Map<String,Object>> bannerMapList = new ArrayList<>();
        for(Banner banner : bannerList) {
            Map<String,Object> map = new HashMap<>(16);
            map.put("id",banner.getId());
            map.put("name",banner.getName());
            bannerMapList.add(map);
        }
        return bannerMapList;
    }

    /**
     * 处理连接
     * @param fontUrl
     * @param type
     * @return
     * @throws IOException
     * @throws UpException
     */
    private String getUrl(String fontUrl,String type) throws IOException, UpException {
        if(fontUrl.contains("?")) {
            fontUrl = fontUrl.split("\\?")[0];
        }
        if(!fontUrl.contains(upyunProperties.getDomain())) {
            if(fontUrl.startsWith("/")) {
                if(upyunService.getFileInfo(fontUrl) == null) {
                    if("play".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.PLAY_ADDRESS_ERROR);
                    }
                    if("logo".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                    }
                }
            } else {
                if(upyunService.getFileInfo("/" + fontUrl) == null) {
                    if("play".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.PLAY_ADDRESS_ERROR);
                    }
                    if("logo".equals(type)) {
                        throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                    }
                }
                fontUrl = "/" + fontUrl;
            }
        } else {
            if(upyunService.getFileInfo(UriUtil.getUri(fontUrl)) == null) {
                if("play".equals(type)) {
                    throw new BussinessException( BizExceptionEnum.PLAY_ADDRESS_ERROR);
                }
                if("logo".equals(type)) {
                    throw new BussinessException( BizExceptionEnum.LOGO_ADDRESS_ERROR);
                }
            }
            fontUrl = UriUtil.getUri(fontUrl);
        }
        return fontUrl;
    }

    /**
     * 校验count为非零正整数
     * @param count
     */
    private void checkCount(Integer count,String type) {
        if(count != null) {
            if(!RegExpValidatorUtil.isIntNumber(String.valueOf(count))) {
                if("share".equals(type)) {
                    throw new BussinessException(BizExceptionEnum.SHARE_COUNT_ERROR);
                }
                if("play".equals(type)) {
                    throw new BussinessException(BizExceptionEnum.PLAY_COUNT_ERROR);
                }
                if("download".equals(type)) {
                    throw new BussinessException(BizExceptionEnum.DOWNLOAD_COUNT_ERROR);
                }
            }
        }
    }

    private String getAgeTypeNames(String[] ageTypeIds) {
        String ageType = "";
        for (int i = 0; i < ageTypeIds.length; i++) {
            Integer ageTypeInt = Integer.parseInt(ageTypeIds[i]);
            if(ageTypeInt == -1) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "所有";
                } else {
                    ageType += ",所有";
                }
            }
            if(ageTypeInt == 1) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "0~1岁";
                } else {
                    ageType += ",0~1岁";
                }
            }
            if(ageTypeInt == 0) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "胎教";
                } else {
                    ageType += ",胎教";
                }
            }
            if(ageTypeInt == 2) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "1~3岁";
                } else {
                    ageType += ",1~3岁";
                }
            }
            if(ageTypeInt == 3) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "3~5岁";
                } else {
                    ageType += ",3~5岁";
                }
            }
            if(ageTypeInt == 4) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "5~7岁";
                } else {
                    ageType += ",5~7岁";
                }
            }
            if(ageTypeInt == 5) {
                if(StringUtils.isBlank(ageType)) {
                    ageType = "7~12岁";
                } else {
                    ageType += ",7~12岁";
                }
            }
        }
        return ageType;
    }
}
